package com.ken.algorithms.linkedList;

/**
 * <ul>
 * <li>Title: SingleLinkedList</li>
 * <li>Description: TODO </li>
 * </ul>
 *
 * @author 程序员ken
 * @date 2021/5/21 0021 上午 9:59
 */
public class SingleLinkedList<E> {
    transient ListNode<E> first; // 头部节点
    transient ListNode<E> curNode;//当前操作节点（因为找不到前置节点，所以需要记录前置节点）
    private  int size;

    //添加元素
    public void add(E e){
        final ListNode  node = new ListNode(e,null);
        if(first==null){
            this.first = node ;
            this.curNode = node ;
        }
        else {
            this.curNode.next = node ;
            this.curNode = node ;
        }
        size++;
    }

    //删除元素
    public boolean remove(int index){
        if(size<=0 || size < index+1){
            return false;
        }
        else{
            if(index==0){
                this.first = this.size>1?this.first.next:null;
                this.size--;
            }
            ListNode<E> prev = first;
            ListNode<E> ln = first;
            int count =0;
            while (ln.next!=null){
                ln = ln.next;
                count++;
                if(count == index-1){
                    prev = ln;//记录上一个节点
                }
                if(count==index){
                    prev.next = ln.next;// 上个节点的下一个节点 等于 删除节点的下一个节点
                    break;
                }
            }
            this.size--;
            return true;
        }
    }


    //取出元素
    public E get(int index){
        if (index >= size){
            throw new IndexOutOfBoundsException(String.format("Index:%s, Size:%s",index,this.size));
        }
        else{
            if(index==0){
                return this.first.item;
            }
            ListNode<E> ln = first;
            int count =0;
            while (ln.next!=null){
                ln = ln.next;
                count++;
                if(count==index){
                    break;
                }
            }
            return ln.item;
        }
    }

    public int size(){
        return this.size;
    }

    // 定义单链表结构
     static class ListNode<E> {
        private E item;
        private ListNode<E> next;

        public ListNode(E item, ListNode<E> next) {
            this.item = item;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
        for (int i = 1; i < 7; i ++) {
            list.add(i*100);
        }
        list.remove(0);
        //list.remove(2);
        System.out.println(list);
        System.out.println(list.get(2));
        System.out.println(list.get(5));
    }

}
